package edu.pku.sei.transformation.editor.binding;

import java.util.Hashtable;
import java.util.List;

import edu.pku.sei.modeler.model.core.MetaPackage;
import edu.pku.sei.modeler.model.structure.MetaDiagram;
import edu.pku.sei.modeler.model.structure.MetaNode;
import edu.pku.sei.transformation.editor.model.Rule;
import edu.pku.sei.transformation.editor.model.Transformation;

public class BindingRecorder {
	private static Hashtable<MetaDiagram, MetaNode> relationNodeTable = new Hashtable<MetaDiagram, MetaNode>();
	private static Hashtable<MetaDiagram, Transformation> transformationTable = new Hashtable<MetaDiagram, Transformation>();

	public static Rule getRelationByDiagram(MetaDiagram diagram) {
		MetaNode relationNode = getRelationNodeByDiagram(diagram);
		if (relationNode != null) {
			return (Rule) relationNode.getModelElement();
		} else {
			return null;
		}
	}

	public static MetaNode getRelationNodeByDiagram(MetaDiagram diagram) {
		MetaNode relationNode = relationNodeTable.get(diagram);
		if (relationNode == null) {
			for (Object obj : diagram.getNodes()) {
				if (obj instanceof MetaNode
						&& ((MetaNode) obj).getModelElement() instanceof Rule) {
					relationNode = (MetaNode) obj;
					relationNodeTable.put(diagram, relationNode);
				}
			}
		}
		return relationNode;
	}

	public static Transformation getTransformationByDiagram(MetaDiagram diagram) {
		Transformation t = transformationTable.get(diagram);
		if (t == null) {
			MetaPackage defaultPackage = (MetaPackage) diagram.getContainer().getContainer();
			List transformations = defaultPackage.getOtherElements();
			for (Object transformation : transformations) {
				if (transformation instanceof Transformation
						&& ((Transformation) transformation).getDiagram() == diagram) {
					t = (Transformation) transformation;
					transformationTable.put(diagram, t);
				}
			}
		}
		return t;
	}
}
